<template>
  <div>
    <div id="app">
      <el-container>
        <!-- 用户列表 -->
        <el-main>
<!--          &lt;!&ndash; 搜索栏 &ndash;&gt;-->
<!--          <el-row>-->
<!--            <el-col :span="8">-->
<!--              <el-input placeholder="用户名/邮箱/手机号" v-model="searchText" clearable></el-input>-->
<!--            </el-col>-->
<!--            <el-col :span="4">-->
<!--              <el-button type="primary" @click="searchUsers">搜索</el-button>-->
<!--            </el-col>-->
<!--          </el-row>-->

          <!-- 用户列表 -->
          <el-table :data="users" style="width: 100%">
            <el-table-column prop="userId" label="用户ID"></el-table-column>
            <el-table-column label="头像">
              <template slot-scope="scope">
                <img class="avatar" :src="scope.row.avatarUrl" alt="头像">
              </template>
            </el-table-column>

            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>

            <el-table-column prop="status" label="用户状态">
              <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status == 1"
                    :active-color="scope.row.status == 1 ? '#409EFF' : '#FF4949'"
                    :inactive-color="scope.row.status == 1 ? '#409EFF' : '#FF4949'"
                    @change="updateUserStatus(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="userType" label="用户类型">
              <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.userType == 0"
                    @change="updateUserType(scope.row)">

                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="deleteUser(scope.$index,scope.row.userId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页器 -->
          <el-pagination
              background
              :page-size="pageSize"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :total="totalUsers"
              @current-change="handlePageChange"
              layout="sizes, prev, pager, next"
              @size-change="handlePageSizeChange">

          </el-pagination>

        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      users: [], // 用户列表数据
      searchText: '',
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数量
      totalUsers: 0, // 用户总数
      pageSizeOptions: [10, 20, 30, 50], // 每页显示数量的选项
      //获取已登录用户信息
      localUser: localStorage.getItem('user') ? JSON.parse(localStorage.user) : null
    }

  },
  mounted() {
    this.fetchUsers();
    this.fetchTotalUsers();
  },
  created(){
    if (this.localUser == null || this.localUser.userType != 0){
      console.log("enter.")
      this.$message({
        message: "非管理员禁止访问！！！",
        type: 'error'
      });
      this.$router.push('/');
    }
    console.log("created.")
  },
  methods: {
    // 获取用户列表
    fetchUsers() {
      const url = `/api/users/selectAllUser?pageNum=${this.currentPage}&pageSize=${this.pageSize}`;
      this.axios.get(url)
          .then(response => {
            this.users = response.data.data;
            this.users.forEach(user => {
              user.avatarUrl = "/api" + user.avatarUrl;
            });
            // console.log(v.users);
          })
          .catch(error => {
            console.error('获取用户列表失败', error);
          });
    },
    // 获取用户总数
    fetchTotalUsers() {
      const url = '/api/users/getTotalUsers';
      this.axios.get(url)
          .then(response => {
            this.totalUsers = response.data.data;
            console.log(this.totalUsers);
          })
          .catch(error => {
            console.error('获取用户总数失败', error);
          });
    },
    // 更新用户状态
    updateUserStatus(user) {
      if (this.localUser.userId === user.userId){
        this.$message({
          message: "禁止修改自己！",
          type: 'error'
        });
        return;
      }


      let status = user.status;
      if (status === 1) {
        status = 0;
      } else {
        status = 1;
      }
      let confirmTxt;
      if (user.status === 0) {
        confirmTxt = "你确定要解封该用户嘛？";
      } else {
        confirmTxt = "你确定要封禁该用户嘛？";
      }
      this.$confirm(confirmTxt, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
          .then(() => {
            // 用户选择是
            this.axios.put(`/api/users/updateUserStatus/${user.userId}/${status}`)
                .then(response => {
                  if (response.data.code === 200) {
                    user.status = status;
                    // console.log('更新用户状态成功');
                    this.$message({
                      message: "更新成功！",
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: "更新失败！",
                      type: 'error'
                    });
                  }

                })
                .catch(error => {
                  console.error('更新用户状态失败', error);
                });
          })
          .catch(() => {
            //取消操作
          });
    },
    // 更新用户类型
    updateUserType(user) {
      if (this.localUser.userId === user.userId){
        this.$message({
          message: "禁止修改自己！",
          type: 'error'
        });
        return;
      }

      let userType = user.userType;
      if (userType === 1) {
        userType = 0;
      } else {
        userType = 1;
      }
      let confirmTxt;
      if (user.userType === 0) {
        confirmTxt = "你确定要取消该用户的管理员身份嘛？";
      } else {
        confirmTxt = "你确定要设置该用户为管理员嘛？";
      }
      this.$confirm(confirmTxt, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
          .then(() => {
            // 用户选择是
            this.axios.put(`/api/users/updateUserType/${user.userId}/${userType}`)
                .then(response => {
                  if (response.data.code === 200) {
                    user.userType = userType;
                    // console.log('更新用户状态成功');
                    this.$message({
                      message: "更新成功！",
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: "更新失败！",
                      type: 'error'
                    });
                  }

                })
                .catch(error => {
                  console.error('更新失败', error);
                });
          })
          .catch(() => {
            //取消操作
          });

    },
    // 删除用户
    deleteUser(i,userId) {
      // v.users;
      if (this.localUser.userId === userId){
        this.$message({
          message: "禁止删除自己！",
          type: 'error'
        });
        return;
      }

      this.$confirm("你确定要删除该用户嘛", '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
          .then(() => {
            // 用户选择是
            this.axios.put(`/api/users/deleteUser/${userId}`)
                .then(response => {
                  if (response.data.code === 200) {
                    this.users.splice(i,1);
                    this.$message({
                      message: "删除成功！",
                      type: 'success'
                    });
                    location.reload();
                  } else {
                    this.$message({
                      message: "删除失败！",
                      type: 'error'
                    });
                  }

                })
                .catch(error => {
                  console.error('删除失败', error);
                });
          })
          .catch(() => {
            //取消操作
          });


    },
    // 处理页码变化
    handlePageChange(currentPage) {
      this.currentPage = currentPage;
      this.fetchUsers();
    },
    // 处理每页显示数量变化
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPage = 1; // 重置当前页码
      this.fetchUsers();
    },
    // 搜索用户
    // searchUsers() {
    //   if (v.searchText.trim() === ""){
    //     v.$message.error("请输入搜索内容");
    //     return;
    //   }
    //   const url = `/api/users/searchUsers/${this.searchText}`;
    //   this.axios.get(url)
    //       .then(response => {
    //         this.users = response.data.data;
    //         this.totalUsers = this.users.length; // 更新总数为搜索结果的数量
    //         this.pageSize = this.users.length;
    //       })
    //       .catch(error => {
    //         console.error('搜索用户失败', error);
    //       });
    // }
  }
};
</script>

<style>


.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 70px;
}
</style>